  function [facmed_mat,cvec_temp] =  out_timedraws(mat, sample, outpath , outname, pvec ); 
% function [facmed_mat,cvec_temp] =  out_timedraws(mat, sample, outpath , outname, pvec ); 
 
% mat          T x p x ndraws 
% sample       calendar vector ( T x 1) trimming inside the code
% outpath      Where to store it 
% Name         File
% pvec        vector of percentiles 
%             default is [0.1 0.32 0.68 0.9 ]

% 
% Alejandro Justiniano 10/24/04
cucd = cd; 
if nargin < 5 
    pvec=[0.05 0.16  0.84 0.95]; 
end
if nargin == 2 
    flag_save = 0 
else 
    flag_save =1 
end 
sample=sample(:) ; 

pvec=pvec(:); 
nump=size( pvec , 1); 
if all( pvec > 1 ) == 1 
    pvec=pvec/100;
end
pvec_cell = num2cellaj( 100*pvec ); 

dim=size(mat); 
if dim(1)~= size( sample , 1); 
    error('Factor matrix and calendar matrix have different rows'); 
end 


fac_cell=emptycell(dim(1)+1, dim(2)*(nump+2)  + 1); 
fac_cell(2:end,1)=num2cellaj(sample); 
fac_cell(1,1) = {'Observations'}; 

numc=dim(2); 

top_cell=[]; 
cpf = nump+2; 
cpf_mat = 2:( size( fac_cell,2)  ); 
cpf_mat = reshape( cpf_mat , cpf , numc )'; 

med_mat = zeros( dim(1) , numc ); 

hh=1; 
for hh=1:numf;
    tstr=['Ser',num2str(hh)]; 
    ii=1; 
    top_cell = cell( 1, nump ); 
    for ii=1:nump; 
        top_cell(ii)={[tstr,' ',num2str(pvec(ii)),'%']}; 
    end 
    pos_col = cpf_mat(hh,:); 
    
    top_cell=[{[tstr,' Mean'] , [tstr,' Med']} top_cell] ; 
    fac_cell( 1, pos_col  ) = top_cell ; 
    temp=squeeze( fac_ch(:,hh,:,:) ); 
    temp=reshape( temp,[dim(1) dim(3)*dim(4)] ); 
    temp=sort(temp,2); 
    fac_mean=squeeze( mean(temp,2) ) ;
    fac_med=squeeze( median(temp,2) ); 
    facmed_mat(:,hh) = fac_med; 
    fac_perc=temp( :, round(dim(3)*dim(4)*pvec) ); 
    fac_cell(2:end , pos_col(1) ) = num2cellaj( fac_mean); 
    fac_cell(2:end , pos_col(2) ) = num2cellaj( fac_med );
    fac_cell(2:end , pos_col(3:end) ) = num2cellaj( fac_perc );
    figure; 
    hold on; 
    plot( cvec_temp  , fac_mean,'-b','LineWidth',1.5 ); 
    plot( cvec_temp  , fac_med ,'--k','LineWidth',1.5 ); 
    plot( cvec_temp  , fac_perc(:,1), ':r','LineWidth',1); 
    plot( cvec_temp  , fac_perc(:,end), ':r','LineWidth',1);
    legend('mean','median',[pvec_cell{1},'%'],[pvec_cell{end},'%'] ); 
    title([root_str,'  Factor ',tstr],'FontSize',10,'FontWeight','bold'); 
    hold off;
    cd(opath_); 
    %save(['fac',tstr'],'fac_perc','fac_mean','pvec' ); 
    saveas(gcf,['g_',tstr],'fig'); 
    cd(cucd); 
    clear temp fac_mean fac_perc;         
end


cd(opath_); 
load ocell; 
if flag_addtop == 1 
    cd(cucd); 
    fac_cell = merge_cells( ocell , fac_cell ); 
end 
cd(opath_)

savecell(fac_cell,cucd,opath_,['tab_fac_',root_str] ); 
disp('================='); 
disp('Saved Factor Cell'); 

